package com.cooba.activitys.login;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cooba.R;
import com.cooba.activitys.user.ForgetPasswordActivity;
import com.cooba.utils.Constants;
import com.cooba.utils.Md5Utils;
import com.cooba.utils.MySqlOpenHelper;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.json.JSONObject;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2015/12/10.
 * 登录
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener, PlatformActionListener {
    private TextView mLogin;
    private TextView mRegistered;
    private TextView mForgetPassword;
    private ImageView mBack_login;
    private EditText mEt_loginNumber, mEt_loginPassword;
    private String COOBA = "COOBA-YANSHI";
    private LinearLayout qq_login;
    private MySqlOpenHelper helper;
    private SQLiteDatabase database;
    private LinearLayout wechat_login;
    private LinearLayout sina_login;
    private RequestParams params;
    private String create_date;
    private String login_id;
    private String uuid;
    private String password;
    private String nickname;
    private String type;
    private String PhoneIp=null;
    private String uuid_url;

    private void bindViews() {
        mBack_login = (ImageView) findViewById(R.id.back_login);
        mLogin = (TextView) findViewById(R.id.login);
        mRegistered = (TextView) findViewById(R.id.registered);
        mForgetPassword = (TextView) findViewById(R.id.forgetPassword);
        mEt_loginNumber = (EditText) findViewById(R.id.et_loginNumber);
        mEt_loginPassword = (EditText) findViewById(R.id.et_loginPassword);
        qq_login = (LinearLayout) findViewById(R.id.qq_login);
        wechat_login = (LinearLayout) findViewById(R.id.wechat_login);
        sina_login = (LinearLayout) findViewById(R.id.sina_login);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        PushAgent.getInstance(this).onAppStart();

        bindViews();
        mRegistered.setOnClickListener(this);
        mBack_login.setOnClickListener(this);
        mLogin.setOnClickListener(this);
        mForgetPassword.setOnClickListener(this);
        mEt_loginNumber.setOnFocusChangeListener(this);
        qq_login.setOnClickListener(this);
        wechat_login.setOnClickListener(this);
        sina_login.setOnClickListener(this);
        ShareSDK.initSDK(this);
        //getLocalMacAddress();
    }

    @Override
    public void onClick(View v) {
        Intent intent;

        final String Number = mEt_loginNumber.getText().toString().trim();
        //final String Password=mEt_loginPassword.getText().toString().trim();
        final String Password = Md5Utils.encodeBy32BitMD5(mEt_loginPassword.getText().toString());
        // TODO: 2015/12/14 phone ip
        /**
         * 获取手机ip地址
         */
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();

                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        PhoneIp = inetAddress.getHostAddress().toString();
                        Log.e("mm", "getPhoneIp" + PhoneIp);
                    }
                }
            }
        } catch (Exception e) {

        }


        switch (v.getId()) {
            //立即注册
            case R.id.registered:
                intent = new Intent(LoginActivity.this, RegisteredActivity.class);
                startActivity(intent);
                //finish();
                break;
            //返回游客登录
            case R.id.back_login:
//                intent = new Intent(LoginActivity.this, MainActivity.class);
//                startActivity(intent);
                finish();
                break;

            //登录
            case R.id.login:
                if (Number.length() > 0 && Password.length() > 0) {
                    GetLoginInfo(Number, Password, PhoneIp);
                } else {
                    if (Number.length() == 0) {
                        Toast.makeText(getApplication(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    } else if (Password.length() == 0) {
                        Toast.makeText(getApplication(), "请输入密码", Toast.LENGTH_SHORT).show();
                    }
                }
                break;

            //忘记密码
            case R.id.forgetPassword:
                intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
                //finish();
                break;


            //QQ登录
            case R.id.qq_login:
                doQQLogin();
                break;
            case R.id.wechat_login:
                doWechatLogin();
                break;
            case R.id.sina_login:
                doSinaLogin();
                break;
        }
    }

    //使用新浪微博登录
    private void doSinaLogin() {
        type = "4";
        Platform plat_sina = ShareSDK.getPlatform(LoginActivity.this, SinaWeibo.NAME);
        plat_sina.SSOSetting(false);
        plat_sina.setPlatformActionListener(this);
        plat_sina.showUser(null);
    }

    //使用微信登录
    private void doWechatLogin() {
        type = "3";
        Platform plat_wechat = ShareSDK.getPlatform(LoginActivity.this, Wechat.NAME);
        plat_wechat.setPlatformActionListener(this);
        plat_wechat.showUser(null);
    }

    //使用QQ登录
    private void doQQLogin() {
        type = "2";
        Platform plat_qq = ShareSDK.getPlatform(LoginActivity.this,
                QZone.NAME);
        plat_qq.SSOSetting(false);
        plat_qq.setPlatformActionListener(this);
        plat_qq.showUser(null);
        //
    }

    private void doRegisterCheck() {
        final HttpUtils httpUtils = new HttpUtils();
        final RequestParams params = new RequestParams();
        params.addBodyParameter("uuid", uuid);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.RegisterCheck, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "校验获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    String msg = JSON.parseObject(responseInfo.result).getString("msg");
                    String status = JSON.parseObject(responseInfo.result).getString("status");
                    if (status.equals("0")) {//已经注册
                        //获取用户信息
                        String login_id = JSON.parseObject(responseInfo.result).getString("login_id");
                        SharedPreferencesUtil.saveData(LoginActivity.this, "login_id", login_id);
                        String name =JSON.parseObject(responseInfo.result).getString("name");
                        SharedPreferencesUtil.saveData(LoginActivity.this, "name", name);
                        Intent intent = new Intent(Constants.UPDATE_DATA);
                        sendBroadcast(intent);
                        finish();

                    } else {
                        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        create_date = sDateFormat.format(new java.util.Date());
                        params.addBodyParameter("login_id", login_id);
                        params.addBodyParameter("login_type", type);
                        params.addBodyParameter("password", password);
                        params.addBodyParameter("name", nickname);
                        params.addBodyParameter("uuid", uuid);
                        params.addBodyParameter("photo",uuid_url);
                        params.addBodyParameter("create_date", create_date);
                        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.Register, params, new RequestCallBack<String>() {
                            @Override
                            public void onFailure(HttpException arg0, String arg1) {
                                Log.e("wei", "获取失败");
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                String status = null;
                                try {
                                    status = JSON.parseObject(responseInfo.result).getString("status");
                                    Log.d("wei", JSON.parseObject(responseInfo.result).getString("msg"));
                                    if (status.equals("1")) {
//                                        GetLoginInfo(login_id,password,PhoneIp);
                                        SharedPreferencesUtil.saveData(LoginActivity.this, "login_id", uuid);
                                        SharedPreferencesUtil.saveData(LoginActivity.this, "password", password);
                                        SharedPreferencesUtil.saveData(LoginActivity.this,"name",nickname);
                                        Intent intent = new Intent(Constants.UPDATE_DATA);
                                        sendBroadcast(intent);
                                        finish();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }


    /**
     * 使用xutils获取登陆接口数据
     **/
    private void GetLoginInfo(String number, final String password, String wifiip) {
        // TODO: 2015/12/13 获取系统时间
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        create_date = sDateFormat.format(new java.util.Date());
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("login_id", number);
        params.addQueryStringParameter("password", password);
        //params.addQueryStringParameter("login_ip", wifiip);
        params.addQueryStringParameter("login_date", create_date);
        Log.e("wei", "number" + number + "  wifiip" + wifiip + "  password" + password + "  create_date" + create_date);
        String url = ServerURL.httpUrl + ServerURL.Login;
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "链接服务器成功" + responseInfo.result);
                String result = null;
                //JSON的解析过程
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                    result = jsonObject.get("status").toString();
                    String msg=jsonObject.get("msg").toString();
                    if (result.equals("0")) {
                        Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
                    } else if (result.equals("1")) {
                        Toast.makeText(LoginActivity.this, "登陆成功!", Toast.LENGTH_LONG).show();
                        String login_id = jsonObject.get("login_id").toString();
                        String name = jsonObject.get("name").toString();
                        //String allintegral = jsonObject.get("allTotalIntegral").toString();
                        SharedPreferencesUtil.saveData(LoginActivity.this, "login_id", login_id);
                        SharedPreferencesUtil.saveData(LoginActivity.this, "password", password);
                        SharedPreferencesUtil.saveData(LoginActivity.this, "name", name);
                        //SharedPreferencesUtil.saveData(LoginActivity.this, "allTotalIntegral", allintegral);
                        Intent intent = new Intent(Constants.UPDATE_DATA);
                        sendBroadcast(intent);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this, "登陆异常!", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(LoginActivity.this, "链接服务器失败", Toast.LENGTH_LONG).show();
                Log.e("ss", "链接服务器失败");
            }
        });
    }

    //手机号码校验
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
        } else {
            if (Utils.isnumber(mEt_loginNumber.getText().toString())) {
            } else {
                Toast.makeText(getApplication(), "请输入正确手机号", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Log.d("wei", "complete");
        if (platform.isValid()) {
            login_id = platform.getDb().getUserId();
            uuid = platform.getDb().getUserId();
            password =Md5Utils.encodeBy32BitMD5("123456");
            nickname = platform.getDb().getUserName();
            Log.d("wei","uuid:"+uuid);
            SharedPreferencesUtil.saveData(getApplicationContext(), "uuid", uuid);
            uuid_url=platform.getDb().getUserIcon();
            doRegisterCheck();
        }
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        throwable.printStackTrace();
        Log.d("wei", "error");
    }

    @Override
    public void onCancel(Platform platform, int i) {
        Log.d("wei", "cancel");
    }


    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
